//导入数据模块
const db = require("../db/mysql")
//导入bcryptjs
const bcrypt = require("bcryptjs")
//获取用户基础信息
exports.getUserInfo = (req, res) => {

    //定义查询sql
    let sql = "SELECT id,username,nickname,email,user_pic FROM en_users WHERE id = ?"

    //调用db.query()方法 执行sql语句
    //从token中获取用户id
    db.query(sql, req.auth.id, (err, results) => {
        if (err) {
            return res.cc(err)
        }
        if (results.length !== 1) {
            return res.cc("用户信息获取失败")
        }
        res.send({
            status: 0,
            message: "用户信息获取成功",
            data: results[0]
        })
    })
}

//更新用户信息接口
exports.updateUserInfo = (req, res) => {
    //定义更新sql
    let sql = "UPDATE en_users SET nickname = ?,email = ? WHERE id = ?"
    //调用db.query()方法，执行sql
    db.query(sql, [req.body.nickname, req.body.email, req.auth.id], (err, results) => {
        if (err) {
            return res.cc(err)
        }
        if (results.affectedRows !== 1) {
            return res.cc("用户信息更新失败")
        }
        res.send({
            status: 0,
            message: "用户信息更新成功",
            data: req.body
        })

    })

}

//修改用户密码
exports.updateUserPwd = (req, res) => {
    //定义修改sql
    let sql = "UPDATE en_users SET password = ? WHERE id = ?"

    //定义sql判断旧密码是否正确
    let sqlQuery = "SELECT password FROM en_users WHERE id = ?"

    db.query(sqlQuery, req.body.id, (err, results) => {
        if (err) {
            return res.cc(err)
        }
        if (results.length !== 1) {
            return res.cc("密码修改失败")
        }
        let isPassword = bcrypt.compareSync(req.body.old_password, results[0].password)
        if (!isPassword) {
            return res.cc("旧密码不正确")
        }
        //执行sql
        //密码加密
        req.body.password = bcrypt.hashSync(req.body.password, 10);
        db.query(sql, [req.body.password, req.auth.id], (err, results) => {
            if (err) {
                return res.cc(err)
            }
            if (results.affectedRows !== 1) {
                return res.cc("密码修修改失败")
            }

            res.send({
                status: 0,
                message: "密码修改成功",
            })

        })

    })


}

//修改用户头像
exports.updateAvatar = (req, res) => {
    //定义sql
    let sql = "UPDATE en_users SET user_pic = ? WHERE id = ?"
    db.query(sql, [req.body.avatar, req.auth.id], (err, results) => {
        if (err) {
            return res.cc(err)
        }
        if (results.affectedRows !== 1) {
            return res.cc("头像修改失败")
        }

        res.cc("头像修改成功", 0)
    })

}














